<?php
/*
parametri POST:
- table[string]: nome della tabella da visualizzare
	default: 'table_view_main' in config.php
- start[int]: offsett della prima riga visualizzata
	default: 0
- limit[int]: numero di righe da visualizzare per pagina
	default: 'table_view_size' in config.php
- fn[string]: da definire per funzioni speciali
	default: "show"
	funzioni:
	- show: visualizza la tabella formattato con il tag table
	- size: ritorna il numero di righe totali della tabella
	- full: stampa tutte le righe della tabella ignorando i limit e start
*/

	include_once "config.php";
	include_once "include/db.php";
	include_once "include/params.php";

	$params = array(
		'table'		=> $GLOBALS['table_view_main'],
		'start'		=> 0,
		'limit'		=> $GLOBALS['table_view_size'],
		'fn'		=> "show"
	);

	function getTableFields($res)
	{
		$ret = array();
		$i = 0;
		while($col=mysql_fetch_field($res))
		{
			$ret[$i]['name'] = $col->name;
			$ret[$i]['type'] = $col->type;
			$i++;
		}
		return $ret;
	}

	function printTableHeader($fields)
	{
		$out = "<tr>";
		foreach( $fields as $f)
			$out .= "\t<td><b>$f[name]</b> ($f[type])</td>\n";
		return $out."</tr>\n";
	}

	function printTable($name, $offset=null, $count=null)
	{
		$db = new CDB();
		$db->connect();
		$limit = $count!=null?
			($offset!=null?"LIMIT $offset, $count":"LIMIT $count"):"";
		$db->query("SELECT * FROM $name $limit");
		$fields = getTableFields($db->last_q);

		$out = "<table width=\"100%\" border=\"0\" bordercolor=\"#000000\" cellpadding=\"1\"
			cellspacing=\"0\" id=\"grid\">\n".printTableHeader($fields);
		while($row=mysql_fetch_array($db->last_q))
		{
			$out .= "\t<tr>\n";
			foreach( $fields as $f)
			{
				$val = $row[$f['name']]!=""?$row[$f['name']]:"&nbsp;";
				$out .= "\n\t<td>$val</td>\n";
			}
			$out .= "\t</tr>\n";
		}
		return $out."</table>";
	}

	function tableSize($name)
	{
		$db = new CDB();
		$db->connect();
		$db->query("SELECT COUNT(*) FROM $name");
		$row = mysql_fetch_array($db->last_q);
		return $row[0];
	}

	paramsFromPost($params);
	switch($params['fn'])
	{
		case "show":
			paramsFromPost($params);
			echo printTable($params['table'], $params['start'], $params['limit']);
			break;
		case "size":
			echo tableSize($params['table']);
			break;
		case "full":
			echo printTable($params['table']);
			break;
		default:
			echo "fail";
	} // switch
?>